package com.yxlgateway.config;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.yxlcommon.common.pojo.RespBean;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * @author: yxl
 * @since: 2021-11-15
 **/
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler({RuntimeException.class})
    public RespBean<String> commonExceptionHandler(RuntimeException exception) {
        return RespBean.fail(exception.getMessage(), "error");
    }

    @ExceptionHandler({DisableLoginException.class})
    public RespBean<String> disableException(DisableLoginException exception, HttpServletRequest servletRequest) {
        return RespBean.fail(exception.getMessage(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(StpUtil.getDisableTime(servletRequest.getParameter("name"))));
    }

    @ExceptionHandler({NotLoginException.class})
    public RespBean<String> disableException(NotLoginException nle, HttpServletResponse httpServletResponse) {
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            httpServletResponse.setStatus(-10001);
            message = "未提供token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            httpServletResponse.setStatus(-10001);
            message = "token无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            httpServletResponse.setStatus(-10001);
            message = "token已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            httpServletResponse.setStatus(-10001);
            message = "token已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            httpServletResponse.setStatus(-10001);
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }

        return RespBean.operationSuccess(message, httpServletResponse.getStatus(), "error");
    }
}
